<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-width="120px"
  >
    <el-form-item :label="$t('page.system.gird.title')" prop="title">
      <el-input
        v-model="formData.title"
        :placeholder="$t('page.system.gird.form.titleRequired')"
      />
    </el-form-item>
    
    <el-form-item :label="$t('page.system.gird.coverImage')" prop="coverImage">
      <div class="cover-upload">
        <el-upload
          class="cover-uploader"
          :action="uploadAction"
          :headers="uploadHeaders"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeUpload"
          accept="image/*"
        >
          <div v-loading="uploadLoading" class="upload-container">
            <el-image
              v-if="formData.coverImageUrl && !uploadLoading"
              :src="formData.coverImageUrl"
              class="cover-image"
              fit="cover"
              :preview-src-list="[formData.coverImageUrl]"
            />
            <div v-else-if="!uploadLoading" class="cover-uploader-icon">
              <span style="font-size: 28px;">+</span>
              <div class="upload-text">{{ $t('page.system.gird.uploadCover') }}</div>
            </div>
            <div v-if="uploadLoading" class="upload-loading-text">
              {{ $t('page.system.gird.uploading') }}
            </div>
          </div>
        </el-upload>
        <div v-if="formData.coverImageUrl && !uploadLoading" class="cover-actions">
          <el-button size="small" @click="removeCoverImage" :loading="removeLoading">
            {{ $t('page.system.gird.removeCover') }}
          </el-button>
        </div>
        <div class="upload-tips">
          {{ $t('page.system.gird.uploadTips') }}
        </div>
      </div>
    </el-form-item>

    <el-form-item :label="$t('page.system.gird.userMembershipId')" prop="userMembershipId">
      <el-input-number
        v-model="formData.userMembershipId"
        :min="1"
        :precision="0"
        style="width: 100%"
        :placeholder="$t('page.system.gird.form.userMembershipIdRequired')"
      />
    </el-form-item>

    <el-form-item :label="$t('page.system.gird.position')" prop="position">
      <el-input-number
        v-model="formData.position"
        :min="0"
        :precision="0"
        style="width: 100%"
        :placeholder="$t('page.system.gird.form.positionPlaceholder')"
      />
    </el-form-item>

    <el-form-item v-if="formData.id" :label="$t('page.system.gird.userId')" prop="userId">
      <el-input-number
        v-model="formData.userId"
        :min="1"
        :precision="0"
        style="width: 100%"
        disabled
      />
    </el-form-item>

    <el-form-item :label="$t('page.system.gird.status')" prop="status">
      <el-select
        v-model="formData.status"
        :placeholder="$t('page.system.gird.form.statusRequired')"
        style="width: 100%"
      >
        <el-option :label="$t('page.system.gird.normal')" :value="1" />
        <el-option :label="$t('page.system.gird.disabled')" :value="0" />
      </el-select>
    </el-form-item>
    
    <el-form-item :label="$t('page.system.gird.description')" prop="description">
      <el-input
        v-model="formData.description"
        type="textarea"
        :rows="3"
        :placeholder="$t('page.system.gird.form.descriptionPlaceholder')"
      />
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue';
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElImage,
  ElInput,
  ElInputNumber,
  ElMessage,
  ElOption,
  ElSelect,
  ElUpload,
} from 'element-plus';
// import { Plus } from '@element-plus/icons-vue';
import type { FormRules, UploadProps } from 'element-plus';
import { useAccessStore } from '@vben/stores';
import { $t } from '#/locales';
import { girdApi } from '../../../../api/system/gird';

interface GirdRecord {
  id?: number;
  userId?: number;
  title: string;
  coverImage?: string;
  coverImageUrl?: string;
  description?: string;
  status: number;
  position?: number;
  userMembershipId: number;
  reminderSent?: boolean;
  viewCount?: number;
}

interface Props {
  formData?: GirdRecord | null;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  submit: [values: GirdRecord];
}>();

const formRef = ref();
const uploadLoading = ref(false);
const removeLoading = ref(false);
const accessStore = useAccessStore();

// 表单数据
const formData = reactive<GirdRecord>({
  title: '',
  status: 1,
  userMembershipId: 1,
  description: '',
});

// 上传相关
const uploadAction = computed(() => '/api/gird/upload/cover');
const uploadHeaders = computed(() => {
  const token = accessStore.accessToken;
  return token ? {
    'Authorization': token,
  } : {};
});

// 表单验证规则
const formRules: FormRules = {
  title: [
    { required: true, message: $t('page.system.gird.form.titleRequired'), trigger: 'blur' },
    { min: 1, max: 100, message: $t('page.system.gird.form.titleLength'), trigger: 'blur' },
  ],
  userMembershipId: [
    { required: true, message: $t('page.system.gird.form.userMembershipIdRequired'), trigger: 'blur' },
  ],
  status: [
    { required: true, message: $t('page.system.gird.form.statusRequired'), trigger: 'change' },
  ],
};

// 监听表单数据变化，设置初始值
watch(
  () => props.formData,
  (newData) => {
    if (newData) {
      Object.assign(formData, newData);
    } else {
      // 重置表单
      Object.assign(formData, {
        title: '',
        status: 1,
        userMembershipId: 1,
        description: '',
        coverImage: '',
        coverImageUrl: '',
        position: undefined,
      });
    }
  },
  { immediate: true, deep: true }
);

// 上传前检查
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isImage) {
    ElMessage.error($t('page.system.gird.form.uploadImageOnly'));
    return false;
  }
  if (!isLt10M) {
    ElMessage.error($t('page.system.gird.form.uploadSizeLimit'));
    return false;
  }
  
  uploadLoading.value = true;
  return true;
};

// 上传成功处理
const handleUploadSuccess: UploadProps['onSuccess'] = (response) => {
  uploadLoading.value = false;
  console.log('上传成功响应:', response);

  // 由于 requestClient 配置了 responseReturn: 'data'，response 直接是数据部分
  // 但可能 response 是对象，需要处理
  let imageUrl = '';
  if (typeof response === 'string') {
    imageUrl = response;
  } else if (response && typeof response === 'object') {
    // 如果是对象，尝试获取 URL
    imageUrl = response.url || response.data || response.path || '';
  }
  
  if (imageUrl) {
    formData.coverImageUrl = imageUrl;
    formData.coverImage = imageUrl.split('/').pop(); // 提取文件名
    ElMessage.success($t('page.system.gird.form.uploadSuccess'));
  } else {
    console.error('无法从响应中提取图片URL:', response);
    ElMessage.error($t('page.system.gird.form.uploadFailed'));
  }
};

// 上传失败处理
const handleUploadError: UploadProps['onError'] = (error) => {
  uploadLoading.value = false;
  console.error('上传失败:', error);
  ElMessage.error($t('page.system.gird.form.uploadFailed'));
};

// 删除封面图片
async function removeCoverImage() {
  if (formData.coverImage) {
    removeLoading.value = true;
    try {
      await girdApi.deleteCoverImage(formData.coverImage);
      formData.coverImage = '';
      formData.coverImageUrl = '';
      ElMessage.success($t('page.system.gird.form.removeSuccess'));
    } catch (error) {
      console.error('删除图片失败:', error);
      ElMessage.error($t('page.system.gird.form.removeFailed'));
    } finally {
      removeLoading.value = false;
    }
  }
}

// 表单提交
function submit() {
  return new Promise((resolve, reject) => {
    formRef.value?.validate((valid: boolean) => {
      if (valid) {
        emit('submit', { ...formData });
        resolve(true);
      } else {
        reject(false);
      }
    });
  });
}

// 暴露方法给父组件
defineExpose({
  submit,
});
</script>

<style scoped>
.cover-upload {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.cover-uploader {
  display: inline-block;
}

.cover-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.cover-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.upload-container {
  min-height: 178px;
  width: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
}

.upload-text {
  font-size: 14px;
  color: #8c939d;
  margin-top: 8px;
}

.upload-loading-text {
  font-size: 14px;
  color: var(--el-color-primary);
  text-align: center;
}

.cover-image {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 4px;
}

.cover-actions {
  text-align: center;
  margin-top: 8px;
}

.upload-tips {
  font-size: 12px;
  color: #8c939d;
  text-align: center;
  margin-top: 4px;
}

/* Loading 样式优化 */
.upload-container :deep(.el-loading-mask) {
  border-radius: 6px;
}

.upload-container :deep(.el-loading-spinner) {
  margin-top: -20px;
}

.upload-container :deep(.el-loading-text) {
  color: var(--el-color-primary);
  font-size: 14px;
  margin-top: 10px;
}
</style>
